package msg

import (
	"fmt"
	error2 "go-web-chathouse/error"
	"go-web-chathouse/model"
	"io/ioutil"
	"os"
	"path"
	"strings"
	"time"
)

/*处理世界消息*/
func HandleWorldMsg(client *model.Client, body string, AllClientsMap map[string]*model.Client) {
	for _, c := range AllClientsMap {
		c.Conn.Write([]byte(client.Name + ":" + body))
	}
}

func SendMsg2Client(msg string, client *model.Client) {
	client.Conn.Write([]byte(msg))
}

//向客户端发送它的聊天日志
func SendLog2Client(client *model.Client, filterName string) {
	//读取聊天日志
	logBytes, e := ioutil.ReadFile("D:/BJBlockChain1801/demos/W4/day1/01ChatRoomII/logs/" + client.Name + ".log")
	error2.SHandleError(e, "ioutil.ReadFile")

	if filterName != "all" {
		//查找与某个人的聊天记录
		//从内容中筛选出带有【filterName#或filterName:】的行，拼接起来
		logStr := string(logBytes)
		targetStr := ""
		lineSlice := strings.Split(logStr, "\n")
		for _, lineStr := range lineSlice {
			if len(lineStr) > 20 {
				contentStr := lineStr[20:]
				if strings.Index(contentStr, filterName+"#") == 0 || strings.Index(contentStr, filterName+":") == 0 {
					targetStr += lineStr + "\n"
				}
			}
		}
		client.Conn.Write([]byte(targetStr))
	} else {
		//查询所有的聊天记录
		//向客户端发送
		client.Conn.Write(logBytes)
	}

}

//将客户端说的一句话记录在【以他的名字命名的文件里】
func WriteMsgToLog(msg string, client *model.Client) {
	root, _ := os.Getwd()
	logFile := root + "logs/" + client.Name + ".log"
	println(path.Dir("/msg"))
	//如果日志文件,则创建
	//打开文件
	file, e := os.OpenFile(
		logFile,
		os.O_CREATE|os.O_WRONLY|os.O_APPEND,
		0644)
	if e != nil && os.IsNotExist(e) {
		//不存在此文件
		file, _ = os.Create(logFile)
	}
	defer file.Close()

	//追加这句话
	logMsg := fmt.Sprintln(time.Now().Format("2006-01-02 15:04:05"), msg)
	file.Write([]byte(logMsg))
}
